let stateAll = false
// 动态渲染购物车列表
// 从localStorage中获取购物车列表数据
function loadCartList(){
    // 从localStorage中获取购物车列表数据
    let cartListStr  = localStorage.getItem('cartlist')
    let cartlist = JSON.parse(cartListStr) || []
    
    // 拼接购物车表格字符串
    let str = ` <table>
                    <tr>
                        <th><input type="checkbox" name="checkAll" ${stateAll?'checked':''}>全选</th>
                        <th>商品图片</th>
                        <th>商品名称</th>
                        <th>单价</th>
                        <th>数量</th>
                        <th>小计</th>
                        <th>操作</th>
                    </tr>`
    let bodystr = cartlist.map(item => {
        return `<tr>
                    <td><input type="checkbox" name="checksingle" ${item.state?'checked':''} data-index="${item.id}"></td>
                    <td>
                        <div><img src="${item.url}" alt=""></div>
                    </td>
                    <td>${item.name}</td>
                    <td>${item.price}</td>
                    <td>
                        <input type="button" name="minus" value="-" data-index="${item.id}" ${item.num ==1?'disabled':''}>
                        <input type="text" name="amount" value="${item.num}">
                        <input type="button" name="plus" value="+" data-index="${item.id}">
                    </td>
                    <td class="single-price">${item.singlePrice}</td>
                    <td>
                        <a href=""></a>
                        <a href="" class="del" data-index="${item.id}">删除</a>
                    </td>
                </tr>`
    })
    str = str + bodystr.join('')+`</table>
                                        <div class="total-price">
                                            <span>合计:</span>
                                            <span class="total-price">${totalPrice()}</span>
                                            <span>元</span>
                                            <div>去结算</div>
                                        </div>`
    // 显示到页面上
    $('#shoppingCart .container').html(str)
}

//操作购物车
function onCart(){
    //删除商品
    $('#shoppingCart .container').on('click','.del',function(e){
        let target = e.target || e.srcElement
        //获取删除商品对应id
        let id = $(target).attr('data-index')
        alert(id)

        //从localStorage中删除商品数据
        let cartListStr = localStorage.getItem('cartlist')
        let cartList = JSON.parse(cartListStr)
        let index = cartList.findIndex(item =>item.id == id)
        cartList.splice(index,1)
        //重新存入localStorage
        localStorage.setItem('cartlist',JSON.stringify(cartList))
    })
    //点击＋号将商品数量加1
    $('#shoppingCart .container').on('click','input[name="plus"]',function(e){
        let target = e.target || e.srcElement
        // 将对应id的商品数量+1
        let id = $(target).attr('data-index')
        let cartListStr = localStorage.getItem('cartlist')
        let cartList = JSON.parse(cartListStr) || []
        let product = cartList.find(item => item.id == id)
        product.num++
        product.singlePrice = (product.num*product.price).toFixed(2)
        localStorage.setItem('cartlist',JSON.stringify(cartList))
        loadCartList()
    })

    //点击－号将商品数量减1
    $('#shoppingCart .container').on('click','input[name="minus"]',function(e){
        let target = e.target || e.srcElement
        //将对应id的商品数量-1
        console.log(target)
        let id  = $(target).attr('data-index')
        let cartListStr = localStorage.getItem('cartlist')
        let cartList = JSON.parse(cartListStr) || []
        let product = cartList.find(item => item.id == id)
        product.num--
        product.singlePrice = (product.num*product.price).toFixed(2)
        localStorage.setItem('cartlist',JSON.stringify(cartList))
        loadCartList()
    })

    //点击全选按钮时，全部商品状态选中
    $('#shoppingCart .container').on('click','input[name="checkAll"]',function(e){
        stateAll = !stateAll //取反
        //将localStorage中所有商品的state状态设置成stateAll的状态
        let cartListStr = localStorage.getItem('cartlist')
        let cartList = JSON.parse(cartListStr) || []
        //遍历cartList数组
        cartList.forEach(item => item.state = stateAll)
        localStorage.setItem('cartlist',JSON.stringify(cartList))
        loadCartList()
    })

    // 点击单个商品选择框时，改变state状态
    $('#shoppingCart .container').on('click','input[name="checksingle"]',function(e){
        let target = e.target || e.srcElement
        let id = $(target).attr('data-index')
        //从localStorage中取出对应id的商品
        let cartListStr = localStorage.getItem('cartlist')
        let cartList = JSON.parse(cartListStr) || []
        let product = cartList.find(item => item.id == id)
        product.state = !product.state

        // 全选框状态
        // every遍历数组每一项，满足条件返回true
        stateAll = cartList.every(item => item.state == true) 
        localStorage.setItem('cartlist',JSON.stringify(cartList))
        loadCartList()
    })
}
//计算商品总价
function totalPrice(){
    //从localStorage中选中state状态为true的商品
    let cartListStr = localStorage.getItem('cartlist')
    let cartList = JSON.parse(cartListStr) || []
    let total = cartList.reduce((s,item)=> s=s+(item.state?Number(item.singlePrice):0),0)
    return total.toFixed(2)
}

//点击首页跳转到主界面index
function jumpToIndex() {
    $('#nav ul').on('click', 'li', function () {
        if ($(this).text() == '首页') {
            location.href = './index.html'
        }
    })
}

loadCartList()
onCart()
jumpToIndex()